package com.service;

import static com.def.GenericDef.ACTION_FLG_ADD;
import static com.def.GenericDef.ACTION_FLG_DELETE;
import static com.def.GenericDef.ACTION_FLG_NEW;
import static com.def.GenericDef.ACTION_FLG_QUERY;
import static com.def.GenericDef.ACTION_FLG_UPDATE;
import static com.def.GenericDef.E_XPCRTBOX_BOX_ALREADY_EXIST;
import static com.def.GenericDef.E_XPCRTBOX_NOT_FOUND;
import static com.def.GenericDef.RETURN_CODE_OK;
import static com.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.def.GenericDef.RETURN_MESG_OK;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dao.IBisDataDao;
import com.dao.IRetBoxDao;
import com.dao.IRetCusPrdInDao;
import com.dao.IRetPrdInfoDao;
import com.icim.service.ICIMBaseService;
import com.model.Bis_data;
import com.model.Ret_box;
import com.model.Ret_cus_prd_in;
import com.model.Ret_prd_info;
import com.tx.Xpmagbox.XpmagboxI;
import com.tx.Xpmagbox.XpmagboxO;
import com.tx.Xpmagbox.XpmagboxOA;
import com.util.MqOpe;
import com.util.Util;

@Scope("prototype")
@Service("XpmagboxService")
public class XpmagboxService extends ICIMBaseService{

	private Logger logger = Logger.getLogger(XpmagboxService.class);
	@Autowired
	private XpmagboxI inTrx;

	@Autowired
	private XpmagboxO outTrx;

	@Autowired
	private IRetBoxDao retBoxDao;

	@Autowired
	private IBisDataDao bisDataDao;

	@Autowired
	private IRetPrdInfoDao retPrdInfoDao;

	@Autowired
	private IRetCusPrdInDao retCusPrdInDao;

	@Autowired
	private MqOpe mqOpe;
	private int BOX_DEFAULT_STAND_QTY = 20;
	private Timestamp current_timestamp;

	public String subMainProc(String strInMsg) {
		logger.info("InTrx is " + strInMsg);
		try {
			current_timestamp = Util.getCurrentTimestamp();
			inTrx = (XpmagboxI) mqOpe.inStr2Obj(strInMsg, inTrx);
			outTrx.setTrx_id("XPCRTBOX");
			outTrx.setType_id("O");
			char action_flg = inTrx.getAction_flg().charAt(0);
			switch (action_flg) {
				case ACTION_FLG_QUERY:
					queryFnc();
					break;
				case ACTION_FLG_ADD:
					addFnc();
					break;
				case ACTION_FLG_UPDATE:
					updateFnc();
					break;
				case ACTION_FLG_DELETE:
					deleteFnc();
					break;
				case ACTION_FLG_NEW:
					autoCreateFnc();
					break;
				case 'L' :
					queryBoxAndRetCusPrdInFnc();
					break;
				default:
					errActionFnc();
			}
			if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
				retBoxDao.flushCurSession();
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		} catch (Exception ex) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(ex.toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			logger.info(mqOpe.obj2Str(outTrx));
		}
		return mqOpe.obj2Str(outTrx);
	}

	private void queryBoxAndRetCusPrdInFnc() {
		String box_id = inTrx.getBox_id();
		String hql = "FROM Ret_box where 1=1 ";
		if (box_id != null) {
			//			ret_box = retBoxDao.get(box_id);
			hql = hql + " and id.box_id ='" + box_id + "'";
		} else {
			if (inTrx.getBox_cate() != null) {
				hql = hql + " and box_cate ='" + inTrx.getBox_cate() + "'";
			}
			if (inTrx.getBox_set_code() != null) {
				hql = hql + " and box_set_code ='" + inTrx.getBox_set_code() + "'";
			}
			if (inTrx.getBox_size() != null) {
				hql = hql + " and box_size ='" + inTrx.getBox_size() + "'";
			}
			if (inTrx.getBox_mkr() != null) {
				hql = hql + " and box_mkr ='" + inTrx.getBox_mkr() + "'";
			}

		}
		List<Ret_box> retBoxList = retBoxDao.find(hql);

		if (retBoxList.isEmpty()) {
			outTrx.setRtn_code(E_XPCRTBOX_NOT_FOUND + "");
			outTrx.setRtn_mesg("not found Box,Please Check");
			return;
		}
		List<XpmagboxOA> oary2List = new ArrayList<XpmagboxOA>();
		for (Ret_box retBox : retBoxList) {

			XpmagboxOA oary2 = new XpmagboxOA();
			oary2.setBox_id(retBox.getBox_id());
			oary2.setStd_qty(retBox.getStd_qty());
			oary2.setBox_size(retBox.getBox_size());
			oary2.setBox_cate(retBox.getBox_cate());
			oary2.setBox_set_code(retBox.getBox_set_code());
			oary2.setBox_mkr(retBox.getBox_mkr());
			Ret_cus_prd_in retCusPrdIn = retCusPrdInDao.get(retBox.getBox_id());
			if(retCusPrdIn != null){
				oary2.setBox_phy_id(retCusPrdIn.getBox_phy_id());
				oary2.setMtrl_pallet_capacity(retCusPrdIn.getMtrl_pallet_capacity());
			}
			oary2.setExt_8(retBox.getExt_8());
			oary2.setExt_9(retBox.getExt_9());
			oary2List.add(oary2);
		}
		if(retBoxList.size() > 1000){
			outTrx.setRtn_code(E_XPCRTBOX_NOT_FOUND + "");
			outTrx.setRtn_mesg("There are too many boxes!!!");
			return;
		}
		outTrx.setOary(retBoxList);
		outTrx.setOary2(oary2List);
		outTrx.setTbl_cnt(retBoxList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void addFnc() {
		String box_id = inTrx.getBox_id();
		String box_size = inTrx.getBox_size();
		Ret_box ret_box = retBoxDao.get(box_id);
		double dZero = 0;
		if (ret_box != null) {
			outTrx.setRtn_code(E_XPCRTBOX_BOX_ALREADY_EXIST + "");
			outTrx.setRtn_mesg("BOX ID Already Exist,Please Check");
			return;
		}
		ret_box = new Ret_box();
		ret_box.setBox_id(box_id);
		ret_box.setBox_size(box_size);
		ret_box.setBox_cate(inTrx.getBox_cate());
		ret_box.setBox_set_code(inTrx.getBox_set_code());
		ret_box.setBox_mkr(inTrx.getBox_mkr());

		ret_box.setBox_stat("EMPT");
		ret_box.setReal_emp("Y");
		ret_box.setValid_flg("Y");
		ret_box.setBox_use_cnt(0);
		//		ret_box.setStd_qty(0);
		ret_box.setPrd_qty(0);
		ret_box.setBox_weight(dZero);
		ret_box.setMdl_weight(dZero);
		ret_box.setMeg_mdl_weight(dZero);
		ret_box.setBnk_flg("0");
		ret_box.setEvt_usr(inTrx.getEvt_usr());
		ret_box.setEvt_cate("BULD");
		ret_box.setEvt_timestamp(current_timestamp);
		ret_box.setBox_rgst_timestamp(current_timestamp);
		ret_box.setEvt_time_d(Util.getDoubleTime());
		ret_box.setPrd_admin_flg("NNNNNNNNNNNNNNNNNNNN");
		ret_box.setExt_8(inTrx.getExt_8());
		ret_box.setExt_9(inTrx.getExt_9());
		String hql = "FROM Bis_data where data_cate ='BXSZ' and data_id ='" + box_size + "'";
		Query query = bisDataDao.getCrSession().createQuery(hql);
		Bis_data bis_data = (Bis_data) query.uniqueResult();
		if (bis_data != null) {
			String boxStdQty = bis_data.getData_item();
			if (boxStdQty != null && !("").equals(boxStdQty)) {
				ret_box.setStd_qty(Integer.valueOf(boxStdQty));
			} else {
				ret_box.setStd_qty(BOX_DEFAULT_STAND_QTY);
			}

		} else {
			ret_box.setStd_qty(BOX_DEFAULT_STAND_QTY);
		}
		retBoxDao.save(ret_box);

		if("Y".equals(inTrx.getHx_empty_flg())){
			Ret_cus_prd_in retCusPrdIn = new Ret_cus_prd_in();
			retCusPrdIn.setMtrl_box_id(inTrx.getBox_id());
			retCusPrdIn.setBox_phy_id(inTrx.getBox_phy_id());
			retCusPrdIn.setMtrl_pallet_capacity(inTrx.getMtrl_pallet_capacity());
			retCusPrdIn.setRcv_timestamp(Util.getCurrentTimestamp());
			retCusPrdIn.setAct_flg("Y");
			retCusPrdInDao.saveOrUpdate(retCusPrdIn);
		}
		queryFnc();
		queryBoxAndRetCusPrdInFnc();
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void autoCreateFnc() {
		String box_id = inTrx.getBox_id();
		String box_size = inTrx.getBox_size();
		Ret_box ret_box = retBoxDao.get(box_id);
		double dZero = 0;
		if (ret_box != null) {
			outTrx.setRtn_code(E_XPCRTBOX_BOX_ALREADY_EXIST + "");
			outTrx.setRtn_mesg("BOX ID Already Exist,Please Check");
			return;
		}
		ret_box = new Ret_box();
		ret_box.setBox_id(box_id);
		ret_box.setBox_size(box_size);
		ret_box.setBox_cate(inTrx.getBox_cate());
		ret_box.setBox_set_code(inTrx.getBox_set_code());
		ret_box.setBox_mkr(inTrx.getBox_mkr());

		ret_box.setBox_stat("EMPT");
		ret_box.setReal_emp("Y");
		ret_box.setValid_flg("Y");
		ret_box.setBox_use_cnt(0);
		//		ret_box.setStd_qty(0);
		ret_box.setPrd_qty(0);
		ret_box.setBox_weight(dZero);
		ret_box.setMdl_weight(dZero);
		ret_box.setMeg_mdl_weight(dZero);
		ret_box.setBnk_flg("0");
		ret_box.setEvt_usr(inTrx.getEvt_usr());
		ret_box.setEvt_cate("BULD");
		ret_box.setEvt_timestamp(current_timestamp);
		ret_box.setBox_rgst_timestamp(current_timestamp);
		ret_box.setEvt_time_d(Util.getDoubleTime());

		ret_box.setStd_qty(Integer.valueOf(box_size));

		retBoxDao.save(ret_box);
		queryFnc();
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void queryFnc() {
		String box_id = inTrx.getBox_id();
		String hql = "FROM Ret_box where 1=1 ";
		if (box_id != null) {
			//			ret_box = retBoxDao.get(box_id);
			hql = hql + " and id.box_id ='" + box_id + "'";
		} else {
			if (inTrx.getBox_cate() != null) {
				hql = hql + " and box_cate ='" + inTrx.getBox_cate() + "'";
			}
			if (inTrx.getBox_set_code() != null) {
				hql = hql + " and box_set_code ='" + inTrx.getBox_set_code() + "'";
			}
			if (inTrx.getBox_size() != null) {
				hql = hql + " and box_size ='" + inTrx.getBox_size() + "'";
			}
			if (inTrx.getBox_mkr() != null) {
				hql = hql + " and box_mkr ='" + inTrx.getBox_mkr() + "'";
			}

		}
		List<Ret_box> retBoxList = retBoxDao.find(hql);

		if (retBoxList.isEmpty()) {
			outTrx.setRtn_code(E_XPCRTBOX_NOT_FOUND + "");
			outTrx.setRtn_mesg("not found Box,Please Check");
			return;
		}
		for (Ret_box retBox : retBoxList) {
			Ret_cus_prd_in retCusPrdIn = retCusPrdInDao.get(retBox.getBox_id());

		}
		outTrx.setOary(retBoxList);
		outTrx.setTbl_cnt(retBoxList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);

	}

	public void updateFnc() {
		String box_id = inTrx.getBox_id();
		String box_size = inTrx.getBox_size();
		String box_set_code = inTrx.getBox_set_code();
		String box_cate = inTrx.getBox_cate();
		String box_mkr = inTrx.getBox_mkr();
		Ret_box ret_box = retBoxDao.get(box_id);
		if (ret_box == null) {
			outTrx.setRtn_code(E_XPCRTBOX_NOT_FOUND + "");
			outTrx.setRtn_mesg("not found Box,Please Check");
			return;
		}
		if (box_size != null) {
			ret_box.setBox_size(box_size);
			String hql = "FROM Bis_data where data_cate ='BXSZ' and data_id ='" + box_size + "'";
			Query query = bisDataDao.getCrSession().createQuery(hql);
			Bis_data bis_data = (Bis_data) query.uniqueResult();
			if (bis_data != null) {
				String boxStdQty = bis_data.getData_item();
				if (boxStdQty != null && !("").equals(boxStdQty)) {
					ret_box.setStd_qty(Integer.valueOf(boxStdQty));
				} else {
					ret_box.setStd_qty(BOX_DEFAULT_STAND_QTY);
				}

			}
		}
		if (box_set_code != null) {
			ret_box.setBox_set_code(box_set_code);
		}
		if (box_cate != null) {
			ret_box.setBox_cate(box_cate);
		}
		if (box_mkr != null) {
			ret_box.setBox_mkr(box_mkr);
		}
		ret_box.setEvt_usr(inTrx.getEvt_usr());
		ret_box.setEvt_cate("UPDB");
		ret_box.setEvt_timestamp(current_timestamp);
		ret_box.setExt_8(inTrx.getExt_8());
		ret_box.setExt_9(inTrx.getExt_9());
		retBoxDao.save(ret_box);
		Ret_cus_prd_in retCusPrdIn = retCusPrdInDao.get(box_id);
		if (retCusPrdIn != null) {
			retCusPrdIn.setBox_phy_id(inTrx.getBox_phy_id());
			retCusPrdIn.setMtrl_pallet_capacity(inTrx.getMtrl_pallet_capacity());
		}else{
			if("Y".equals(inTrx.getHx_empty_flg())){
				retCusPrdIn = new Ret_cus_prd_in();
				retCusPrdIn.setMtrl_box_id(inTrx.getBox_id());
				retCusPrdIn.setBox_phy_id(inTrx.getBox_phy_id());
				retCusPrdIn.setMtrl_pallet_capacity(inTrx.getMtrl_pallet_capacity());
				retCusPrdIn.setRcv_timestamp(Util.getCurrentTimestamp());
				retCusPrdIn.setAct_flg("Y");
				retCusPrdInDao.saveOrUpdate(retCusPrdIn);
			}
		}


		queryFnc();
		queryBoxAndRetCusPrdInFnc();
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void deleteFnc() {
		String box_id = inTrx.getBox_id();
		Ret_box ret_box = retBoxDao.get(box_id);
		if (ret_box == null) {
			outTrx.setRtn_code(E_XPCRTBOX_NOT_FOUND + "");
			outTrx.setRtn_mesg("not found Box,Please Check");
			return;
		}
		List<Ret_prd_info> prdInfoList = new ArrayList<Ret_prd_info>();
		prdInfoList = retPrdInfoDao.getShtListInfo(box_id);
		if (null != prdInfoList) {
			outTrx.setRtn_code(E_XPCRTBOX_NOT_FOUND + "");
			outTrx.setRtn_mesg("box is in used,Please Check");
			return;
		}
		ret_box.setEvt_cate("DELB");
		ret_box.setEvt_timestamp(current_timestamp);
		retBoxDao.delete(ret_box);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void errActionFnc() {
		outTrx.setTrx_id("XPCRTBOX");
		outTrx.setType_id("O");
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
	}

}
